import {Component, OnInit} from '@angular/core';
import {format, startOfMonth, endOfMonth} from 'date-fns';
import {MenuItemModel} from "../../../core/auth/auth.service";
import {FetchService} from "../../../core/net/fetch.service";
import {OneMapService} from "../../one-map/one-map.service";
import {NzMessageService} from "ng-zorro-antd";
import {FormBuilder, FormGroup} from "@angular/forms";

@Component({
  selector: 'app-domestic-water',
  templateUrl: './domestic-water.component.html',
  styleUrls: ['./domestic-water.component.scss']
})
export class DomesticWaterComponent implements OnInit {
  yearValue = 2020;
  monthPickerValue;
  rangePickerValue = [startOfMonth(new Date()), endOfMonth(new Date())];

  treeData;
  treeSearchValue = '';
  menuList: Array<MenuItemModel>;
  defaultKeys;
  expandKeys;

  stadiaCode: string = ''; //  当前测站编码
  stadiaParentCode: string = ''; //  当前测站编码
  stationName: string = '';

  processOpt: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        animation: false,
        label: {
          backgroundColor: '#505765'
        }
      }
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: [
      {
        name: 'm³',
        type: 'value'
      }
    ],
    series: [
      {
        name: '补水量',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: '累计补水量',
        type: 'line',
        smooth: true,
        data: []
      }
    ]
  };
  processOptChange: any = {};
  //  水位流量日期选择 默认今天
  featureForm: FormGroup;


  /******************* 监测数据 *******************/
  tableData = [];
  pageNum = 1;
  pageSize = 10;
  /******************* end *******************/

  /******************* 历史同期对比 *******************/
  hType = 'val';
  historyTypes = [{label: '补水量', value: 'val'}, {label: '累计补水量', value: 'valTotal'}];
  historyYear1: Date = new Date('2017');
  historyYear2: Date = new Date('2020');
  historyRangeValue = [startOfMonth(new Date()), endOfMonth(new Date())];
  historyOpt: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: [this.historyYear1, this.historyYear2]
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: this.historyYear1,
        type: 'line',
        data: []
      },
      {
        name: this.historyYear2,
        type: 'line',
        data: []
      }
    ]
  };
  historyOptChange: any = {};

  /******************* end *******************/

  constructor(private fetchService: FetchService,
              private mapService: OneMapService,
              private message: NzMessageService,
              private fb: FormBuilder) {
    this.featureForm = this.fb.group({
      maxVal: [''],
      minVal: [''],
      maxTime: [''],
      minTime: [''],
      avgVal: [''],
      medianVal: [''],
      last3AvgVal: [''],
      last3MedianVal: [''],
      compareWarning: [''],
      compareSecure: [''],
    });
  }

  ngOnInit(): void {
    this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {apicode: 21}).subscribe(res => {

      this.treeData = [
        {
          title: '国电石嘴山第一发电有限公司',
          key: '1',
          isLeaf: true,
        },
        {
          title: '国电宁夏石嘴山发电有限公司',
          key: '2',
          isLeaf: true,
        },
        {
          title: '华电宁夏灵武发电有限公司',
          key: '3',
          isLeaf: true
        },
        {
          title: '石嘴山市润泽供排水有限公司',
          key: '4',
          isLeaf: true
        },
        {
          title: '华能宁夏大坝发电有限公司',
          key: '5',
          isLeaf: true
        },
        {
          title: '中宁发电有限责任公司',
          key: '6',
          isLeaf: true
        },
        {
          title: '宁夏大唐国际大坝发电有限责任公司',
          key: '7',
          isLeaf: true
        },
        {
          title: '西部机场集团宁夏有限公司',
          key: '8',
          isLeaf: true
        },
        {
          title: '宁东水务有限责任公司',
          key: '9',
          isLeaf: true
        },
        {
          title: '长城水务有限责任公司',
          key: '10',
          isLeaf: true
        },
        {
          title: '中国石化长城能源化工（宁夏）有限公司',
          key: '11',
          isLeaf: true
        }, {
          title: '中铝宁夏能源集团有限公司马莲台发电厂',
          key: '12',
          isLeaf: true
        }, {
          title: '国家电投集团宁夏能源铝业有限公司临河发电分公司',
          key: '13',
          isLeaf: true
        },
        {
          title: '宁夏宝丰能源集团股份有限公司',
          key: '14',
          isLeaf: true
        },
        {
          title: '宁夏京能宁东发电有限责任公司',
          key: '15',
          isLeaf: true
        },
        {
          title: '青铜峡铝业股份有限公司宁东铝业分公司',
          key: '16',
          isLeaf: true
        },
        {
          title: '宁夏枣泉发电有限责任公司',
          key: '17',
          isLeaf: true
        },


      ];
      this.defaultKeys = ['1'];
      this.checkDetail(this.treeData[0]);
    });
  }

  monthPickerChange(e): void {
    const start = startOfMonth(new Date(this.yearValue, e, 1));
    const end = endOfMonth(new Date(this.yearValue, e, 1));
    this.rangePickerValue = [start, end];
    console.log(start);
    console.log(end);
  }

  rangePickerValueChange(e): void {
    this.yearValue = null;
    this.monthPickerValue = null;
  }

  checkDetail(node): void {
    this.stationName = node.title;
    this.stadiaCode = node.key;
    this.stadiaParentCode = node.pid;
    this.queryInfo();
  }

  queryInfo(): void {
    if (this.stadiaCode && !this.stadiaCode.includes('m')) {
      this.onQueryProcessList();
      this.onQueryHistory();
    }
  }

  onQueryProcessList() {
    const url = 'report/ecology/data';
    const params = {
      frId: this.stadiaParentCode.replace(/m/, ''),
      lwId: this.stadiaCode,
      stDate: format(this.rangePickerValue[0], 'YYYY-MM-DD'),
      edDate: format(this.rangePickerValue[1], 'YYYY-MM-DD')
    };
    this.fetchService.post<any>(url, params).subscribe(res => {
      this.featureForm.patchValue(res);
      this.tableData = res['originalDataList'];
      const commonOpt = {
        legend: {
          data: ['补水量', '累计补水量'],
          bottom: 10
        },
        xAxis: {
          data: this.getItemValues(this.tableData, 'time')
        }
      };
      this.processOptChange = {
        ...commonOpt, ...{
          series: [
            {
              name: '补水量',
              type: 'line',
              itemStyle: {
                normal: {
                  color: '#289df5', // 折线条的颜色
                  borderColor: '#289df5', // 拐点边框颜色
                  areaStyle: {
                    type: 'default',
                    opacity: 0.1
                  }
                }
              },
              data: this.getItemValues(this.tableData, 'val')
            },
            {
              name: '累计补水量',
              type: 'line',
              itemStyle: {
                normal: {
                  color: '#fbc01b',
                  borderColor: '#fbc01b',
                  areaStyle: {
                    type: 'default',
                    opacity: 0.1
                  }
                }
              },
              data: this.getItemValues(this.tableData, 'valTotal')
            }
          ]
        }
      };
    });
  }

  onQueryHistory() {
    const url = 'report/ecology/hisCampare';
    const param2 = {
      frId: this.stadiaParentCode.replace(/m/, ''),
      lwId: this.stadiaCode,
      stDate: format(this.historyRangeValue[0], 'MM-DD'),
      edDate: format(this.historyRangeValue[1], 'MM-DD'),
      years: this.historyYear1.getFullYear() + ',' + this.historyYear2.getFullYear()
    };
    this.fetchService.post<any>(url, param2).subscribe(res => {
      console.log(res);
      this.changeHistoryChart(res);
    });
  }

  changeHistoryChart(lists) {

    const tempList = lists[0].list.length > 0 ? lists[0] : lists[1];
    const xAxisData = tempList.list.map(item => {
      return item.time.substr(5);
    });
    const legendData: any[] = [];
    const seriesData: any[] = [];
    const itemStyles = [
      {
        normal: {
          color: '#289df5', // 折线条的颜色
          borderColor: '#289df5', // 拐点边框颜色
          areaStyle: {
            type: 'default',
            opacity: 0.1
          }
        }
      },
      {
        normal: {
          color: '#fbc01b',
          borderColor: '#fbc01b',
          areaStyle: {
            type: 'default',
            opacity: 0.1
          }
        }
      },
    ];
    lists.map((line, index) => {
      legendData.push(line.year);
      seriesData.push({
        name: line.year,
        type: 'line',
        smooth: true,
        itemStyle: itemStyles[index % 2],
        data: line.list.map(item => {
          return item[this.hType];
        })
      });
    });
    this.historyOptChange = {
      legend: {
        data: legendData
      },
      xAxis: {
        data: xAxisData
      },
      series: seriesData
    };
    console.log(this.historyOptChange);
  }

  private getItemValues(list, key) {
    return list.map(i => {
      return i[key] || 0;
    });
  }

}
